package cn.itsource.basic.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.itsource.basic.domain.UserInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class GetUserInfoUtil {


    public static Long getUserId(){
        UserInfo userInfo = getUserInfo();
        return userInfo.getId();
    }

    private static UserInfo getUserInfo() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        RedisService redisService = SpringUtil.getBean(RedisService.class);
        UserInfo userInfo = redisService.getKeyObjectValue(token, UserInfo.class);
        Optional.ofNullable(userInfo).orElseThrow(() -> new RuntimeException("当前从redis取出的数据为null"));
        return userInfo;
    }

    public static Long getShopId(){
        UserInfo userInfo = getUserInfo();
        Optional.ofNullable(userInfo.getShopId()).orElseThrow(() -> new RuntimeException("当前登录的员工不是后台员工"));
        return userInfo.getShopId();
    }
}
